#include "cachemonitor.h"

#include "Panel.h"



CacheMonitor::CacheMonitor(Ui::Index *ui,QObject *parent)
    : QObject{parent}
{
    this->ui = ui;
    srand(time(NULL));
    init();
}

void CacheMonitor::init()
{
    getCache();
    initBaseInfo();
    initCmdStatisticsView();
    Panel *p = new Panel(info.value("used_memory_human").toString());
    p->setParent(ui->graphicsView_2);
    dlg = new CmdDlg();
}

void CacheMonitor::getCache()
{
    QByteArray *data = api.cache();
    QJsonObject obj = QJsonDocument::fromJson(*data).object().value("data").toObject();
    commandStats = obj.value("commandStats").toArray();
    info = obj.value("info").toObject();
    dbSize = obj.value("dbSize").toInt();
}

void CacheMonitor::initCmdStatisticsView()
{
    //创建图表
    QChart *chart = new QChart;
    chart->legend()->setVisible(0);//不显示图例
    //创建饼状图序列
    pieSeries = new QPieSeries;
    connect(pieSeries,&QPieSeries::hovered,this,[=](QPieSlice *slice, bool state){
        dlg->close();
        dlg->c = slice->color();

        dlg->label->setText(QString("%1:%2(%3%)").arg(slice->label())
                                .arg(slice->value()).arg(QString::number(slice->value()/cmdSum*100,'f', 2)));
        QPoint pos = QCursor::pos();
        dlg->move(pos.x() + 20,pos.y() + 20);
        slice->setExploded(state);
        if(state){
            dlg->show();
        }else{
            dlg->close();
        }
    });
    pieSeries->setHoleSize(0.1);
    //设置饼状图数据
    QList<SliceInfo> piesInfo;
    for (int i = 0; i < commandStats.size(); ++i) {
        QJsonObject o = commandStats.at(i).toObject();
        // 生成随机颜色值的 R、G、B 分量
        int red = randomColor();
        int green = randomColor();
        int blue = randomColor();
        QColor c(red,green,blue);
        int sum = o.value("value").toString().toInt();
        cmdSum += sum;
        piesInfo.append(SliceInfo(sum,o.value("name").toString(),c));
    }
    // 排序
    QList<QPieSlice*> pies = sortPie(piesInfo);
    for (int i = 0; i < pies.size(); i++) {
        pies.at(i)->setLabelColor(pies.at(i)->color());
        pieSeries->append(pies.at(i));
    }
    //更新标签
    QList<QPieSlice*> list_pies = pieSeries->slices();
    qreal factor = 0.15; //默认值
    for (int i = 0; i < list_pies.size(); i++) {
        //占比10%以下切片的臂长
        if ( list_pies[i]->percentage() < 0.1) {
            list_pies[i]->setLabelArmLengthFactor(factor);
            factor += 0.1;  //参数视界面大小而定
            //调整起始、结束角度. 目的是将数值较小的区域调整到右下角
            if (pieSeries->pieStartAngle() < 135) {
                pieSeries->setPieStartAngle(135);
                pieSeries->setPieEndAngle(360 + 135);
            }
        }
    }

    pieSeries->setLabelsVisible(true);//设置饼图划分的提示
    //将饼状图加入图表
    chart->addSeries(pieSeries);
    //将图表加入画布
    ui->cmdStatisticsView->setRenderHint(QPainter::Antialiasing); // 抗锯齿
    ui->cmdStatisticsView->setChart(chart);
}

QList<QPieSlice *> CacheMonitor::sortPie(QList<SliceInfo> &slicesInfo)
{
    // 1. 排序 value "小大小大"  的顺序排列
    QList<SliceInfo> sortSliceInfo;
    bool bMin  = true;
    int count = slicesInfo.size();
    for (int i = 0; i < count; i++) {
        int index = 0;
        for (int j = 1; j < slicesInfo.size(); j++) {
            if (bMin) { // 取最小数
                if (slicesInfo.at(index).m_value > slicesInfo.at(j).m_value) {
                    index = j;
                }
            } else { // 取最大数
                if (slicesInfo.at(index).m_value < slicesInfo.at(j).m_value) {
                    index = j;
                }
            }
        }

        SliceInfo info = slicesInfo.takeAt(index);
        sortSliceInfo.append(info);

        // 交替取大小数
        bMin = !bMin;
    }

    // 2. 创建
    QList<QPieSlice*> slices;
    for (int i = 0; i < sortSliceInfo.size(); i++) {
        QPieSlice *pieSlice = new QPieSlice(sortSliceInfo.at(i).m_labelName, sortSliceInfo.at(i).m_value);
        pieSlice->setColor(sortSliceInfo.at(i).m_color);
        slices.append(pieSlice);
    }

    return slices;
}

int  CacheMonitor::randomColor()
{
    return std::rand() % 256; // 生成 0 到 255 之间的随机整数作为颜色分量
}

void CacheMonitor::initBaseInfo()
{
    ui->label_RedisVersion->setText(info.value("redis_version").toString());
    ui->label_runMode->setText(info.value("redis_mode").toString() == "standalone" ? "单机" : "集群");
    ui->label_port->setText(info.value("tcp_port").toString());
    ui->label_clientNum->setText(info.value("connected_clients").toString());
    ui->label_runTime->setText(info.value("uptime_in_days").toString());
    ui->label_useMemory->setText(info.value("used_memory_human").toString());
    double useCpu = info.value("used_cpu_user_children").toString().toDouble();
    ui->label_useCPU->setText(QString::number(useCpu, 'f', 2));
    ui->label_memoryConfigure->setText(info.value("maxmemory_human").toString());
    ui->label_AOF->setText(info.value("aof_enabled").toString() == "0" ? "否" : "是");
    ui->label_RDB->setText(info.value("rdb_last_bgsave_status").toString());
    ui->label_keyNum->setText(QString::number(dbSize));
    ui->label_netIO->setText(info.value("instantaneous_input_kbps").toString() + "kps/"
                              + info.value("instantaneous_output_kbps").toString() + "kps");
}
